package com.chat.module.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.comment.core.ResponseResult;
import com.comment.exception.ServiceException;
import com.chat.module.message.domain.ChatInfoLog;
import com.chat.module.message.mapper.ChatInfoLogMapper;
import com.chat.module.message.service.impl.ChatInfoLogServiceImpl;
import com.chat.module.user.domain.User;
import com.chat.module.user.service.IUserService;
import com.comment.pojo.domain.chat.WsMessage;
import com.comment.dubbo.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.module.user.mapper.UserMapper;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.*;

/**
 * (User)表服务实现类
 *
 * @author cxy
 * @since 2024-12-16 15:33:35
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private ChatInfoLogServiceImpl chatInfoLogService;
    @Resource
    private ChatInfoLogMapper chatInfoLogMapper;
    @Resource
    private ChatService messageService;


    @Override
    public boolean updateById(User entity) {
        boolean b = super.updateById(entity);
        if (b) {
            messageService.sendMessageToUser(entity.getUserId(), ResponseResult.upate("user", entity));
        }
        return b;
    }

    @Override
    public void checkFriendsMaxSize(Long userId) {
        // 判断3:对方好友已满50个无法添加好友
        User userFriend = getById(userId);
        if (userFriend.friendIds.size() > 50) {
            throw new ServiceException("好友申请数量超过50人了");
        }
    }

    @Override
    public void checkBothSides(Long sendUserId, Long receiverUserId) {
        if (Objects.equals(sendUserId, receiverUserId)) {
            throw new ServiceException("不能和自己");
        }

        User my = getById(sendUserId);
        if (my.getBlackList().contains(receiverUserId)) {
            throw new ServiceException("你已被对方拉入黑名单");
        }
        User f = getById(receiverUserId);
        if (f.getBlackList().contains(sendUserId)) {
            throw new ServiceException("对方已将你拉入黑名单");
        }
    }

    @Override
    public void tryLogRecentContacts(
            WsMessage wsMessage,// 发送的消息
            Long... userIds // 接收人
    ) {
        Long sendUserId = wsMessage.getSendUserId();
        Set<Long> userList = new HashSet<>(Arrays.asList(userIds));
        ChatInfoLog one = chatInfoLogService.getChatInfoLog(userList);
        if (one == null) {
            // 创建会话记录
            one = new ChatInfoLog();
            one.setUserIds(userList);
            one.setMessageIds(new HashSet<>());
            one.insert();
        }
        one.messageIds.add(wsMessage.getId());
        one.updateById();

        for (Long userId : userIds) {
            User user = getById(userId);
            if (!sendUserId.equals(userId)) {
                user.recentContacts.add(sendUserId);
            }

            updateById(user);
        }
    }


    @Override
    public void tryInit(Long playerId) {
        User friends = new User(playerId, null, null, null, null, null);
        long count = count(new LambdaQueryWrapper<>(friends));
        if (count == 0) {
            friends.insert();
        }
    }

    @Override
    public void addFriend(Long sendUserId, Set<Long> userIds) {
        ArrayList<Exception> exceptions = new ArrayList<>();
        for (Long receiverUserId : userIds) {
            try {
                checkBothSides(sendUserId, receiverUserId);
                checkFriendsMaxSize(sendUserId);
                checkFriendsMaxSize(receiverUserId);
            } catch (Exception e) {
                exceptions.add(e);
            }

            User targetFriend = getById(receiverUserId);
            targetFriend.skipList.add(sendUserId);
            updateById(targetFriend);
        }
        if (!exceptions.isEmpty()) {
            log.error("添加好友异常{}", exceptions);
        }
    }

    /**
     * 拉黑
     */
    public User blackout(Long userId, Set<Long> userIds) {
        User byId = getById(userId);
        for (Long targetUid : userIds) {
            byId.blackList.add(targetUid);
            updateById(byId);
        }
        return byId;
    }

    public User releaseBlackout(Long userId, Set<Long> userIds) {
        User byId = getById(userId);
        for (Long targetUid : userIds) {
            byId.blackList.remove(targetUid);
            updateById(byId);
        }
        return byId;
    }

    public User agreeAddFriend(Long userId, Set<Long> userIds) {
        User byId = getById(userId);
        for (Long id : userIds) {
            if (byId.skipList.remove(id)) {
                byId.friendIds.add(id);
            }
        }
        updateById(byId);
        for (Long id : userIds) {
            User targetFriend = getById(id);
            targetFriend.skipList.remove(userId);
            targetFriend.friendIds.add(userId);
            updateById(targetFriend);
        }
        return byId;
    }

    public User refuseAddFriend(Long userId, Set<Long> userIds) {
        User byId = getById(userId);
        for (Long id : userIds) {
            byId.skipList.remove(id);
        }
        updateById(byId);
        return byId;
    }

    public User deleteFriend(Long userId, Set<Long> userIds) {
        User byId = getById(userId);
        for (Long id : userIds) {
            byId.friendIds.remove(id);
        }
        updateById(byId);
        for (Long id : userIds) {
            User targetFriend = getById(id);
            targetFriend.friendIds.remove(userId);
        }
        return byId;
    }

    public void inspect(Long playerUid) {
        // long l = count(new LambdaQueryWrapper<User>().eq(User::getUserId, playerUid));
        // if (l != 1) {
        //     throw new ServiceException("用户不存在");
        // }
    }
}

